import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_note/note/base.dart';
import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/utils.dart';
import 'package:flutter_note/note/widgets.dart';

class NoteDetailPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _NoteDetailState();
  }
}

class _NoteDetailState extends BaseState<NoteDetailPage> {
  ReplyNote _note;
  NoteManager _noteManager;
  CommentManager _commentManager;
  TextEditingController _commentController = TextEditingController();
  List<ReplyComment> _commentList = List<ReplyComment>();
  FocusNode _focusNode = new FocusNode();
  bool _isMark = false;

  @override
  void initState() {
    super.initState();
    _noteManager = NoteManager.getInstance();
    _commentManager = CommentManager.getInstance();
    _note = _noteManager.getCurrentNote();
    _commentList = _commentManager.getCommentList();
    _initData();
  }

  void _initData() async {
    //await Future.delayed(Duration(milliseconds: 200));
    if (EmptyUtils.isEmpty(_commentList)) {
      //如果列表是空的,先从服务器拉取,如果有内容直接显示
      await _commentManager.loadData(_note.nid); //必须要await,不然拉取了不能更新
    }
    _commentList = _commentManager.getCommentList();
    Reply reply = await MarkManager.getInstance().getMark(_note.nid);
    if (reply.code == Const.SUCCESS) {
      _isMark = true;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      appBar: AppBar(
        title: Text('日记详情'),
        elevation: dim.x2,
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              _addMark();
            },
            child: Container(
                color: Colors.transparent,
                width: dim.x60,
                child: _isMark ? Icon(Icons.star) : Icon(Icons.star_border)),
          )
        ],
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return Column(
      children: <Widget>[
        Expanded(
          flex: 1,
          child: SingleChildScrollView(
            child: Container(
              height: SystemUtils.getScreenHeight(context) -
                  dim.x100 -
                  SystemUtils.getSysStatsHeight(context),
              child: ListView(
                children: <Widget>[
                  NoteView(
                    _note,
                    () {},
                  ),
                  _commentListView(),
                ],
              ),
            ),
          ),
        ),
        Container(
          child: _reComment(),
        ),
      ],
    );
  }

  Widget _commentListView() {
    if (EmptyUtils.isEmpty(_commentList)) {
      return Container(
        color: color.bg_page,
        alignment: Alignment.center,
        child: Text(
          '还没有任何评论',
          style: TextStyle(fontSize: dim.t16, color: color.txt9),
        ),
      );
    } else {
      return Container(
        color: color.bg_page,
        height: SystemUtils.getScreenWidth(context),
        padding: EdgeInsets.only(top: dim.x5),
        child: ListView.builder(
          shrinkWrap: false,
          //列表控件
          itemCount: _commentList.length,
          itemBuilder: (BuildContext context, int position) {
            return CommentView(
              _commentList[position],
              () {},
            );
          },
        ),
      );
    }
  }

  Widget _reComment() {
    return EnsureVisibleWhenFocused(
      focusNode: _focusNode,
      child: Container(
        color: color.bg_page,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  border: Border.all(color: color.line, width: dim.x01),
                  color: color.white,
                  borderRadius: BorderRadius.all(Radius.circular(dim.x150))),
              //height: Dim.x40,
              margin: EdgeInsets.only(
                  right: dim.x10, left: dim.x10, top: dim.x5, bottom: dim.x5),
              alignment: Alignment.centerLeft,
              child: TextField(
                maxLines: null,
                controller: _commentController,
                keyboardType: TextInputType.text,
                style: TextStyle(fontSize: dim.t16, color: color.txt3),
                decoration: InputDecoration(
                  hintText: '请输入评论',
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(
                      left: dim.x15,
                      bottom: dim.x10,
                      top: dim.x10,
                      right: dim.x35),
                ),
                focusNode: _focusNode,
              ),
            ),
            Container(
              alignment: Alignment.bottomRight,
              margin: EdgeInsets.only(right: dim.x15),
              child: InkWell(
                onTap: () {
                  _sendComment();
                },
                child: Container(
                  height: dim.x35,
                  width: dim.x35,
                  child: ClipOval(
                    child: Container(
                      color: color.green,
                      child: Icon(Icons.arrow_upward, color: color.white),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //发送评论
  _sendComment() async {
    show();
    Reply reply =
        await _commentManager.sendComment(_note.nid, _commentController.text);
    dismiss();
    //await Future.delayed(Duration(milliseconds: 50), _sendResult(reply));
    _sendResult(reply);
  }

  _sendResult(Reply reply) {
    setState(() {
      if (reply.code == Const.SUCCESS) {
        _commentController.clear();
        _commentList = _commentManager.getCommentList();
      } else {
        showMessage('发送评论失败'); //发送失败,直接提示
      }
    });
  }

  //添加关注
  _addMark() async {
    if (_isMark) {
      Reply reply = await MarkManager.getInstance().deleteMark(_note.nid);
      if (reply.code == Const.SUCCESS) {
        _isMark = false;
        setState(() {});
      } else {
        showMessage('取消关注失败'); //发送失败,直接提示
      }
    } else {
      Reply reply = await MarkManager.getInstance().addMark(_note.nid);
      if (reply.code == Const.SUCCESS) {
        _isMark = true;
        setState(() {});
      } else {
        showMessage('添加关注失败'); //发送失败,直接提示
      }
    }
  }
}
